<template>
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span style="fontSize : 16px">发表文章</span>
        </div>
        <div class="from">
            <el-form ref="form" :model="form" :rules="rules" >
                <el-form-item label="文章标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题" ></el-input>
                </el-form-item>
                <el-form-item label="文章分类" prop="cate_id" >
                    <el-select v-model="form.cate_id" @blur="$refs.form.validateField('cate_id')" placeholder="请选择分类"  >
                        <el-option v-for="(item) in classData" :key= "item.id" :label="item.cate_name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 富文本编辑器 -->
                <el-form-item label="文章内容" prop="content">
                    <quillEditor v-model="form.content" @blur="$refs.form.validateField('content')" ></quillEditor>
                </el-form-item>
                <!-- 文章封面模块 -->
                <el-form-item label="文章封面">
                    <img v-if="!src"  src="./assets/cover.jpg"  alt='图片预览' />
                    <img v-else ref="previewImage"  :src="src"  alt='图片预览' />
                    <div class="filelabel">
                        <label for="inputFile" style="color : #4F81FF">+ <span style="textDecoration:underline">选择封面</span> </label>
                        <input ref="inputFile" style="display:none"  id="inputFile"  @change="Imgchange"  type="file" accept="image/*" />
                    </div>
                </el-form-item>
                <div class="buttons">
                    <el-form-item>
                        <el-button class="sendButton" @click="onSubmit('已发布')">发布</el-button>
                        <el-button class="saveButton" @click="onSubmit('草稿')">存为草稿</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
    </el-card>
</template>

<script>
import { InitClass, publishArticle, getArticle, changeArticle } from '@/api/other'
// 局部注册富文本编辑器
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

export default {
  data () {
    const select = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择分类!'))
        return false
      } else {
        callback()
      }
    }
    return {
      form: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      id: '',
      changeForm: {},
      classData: [],
      src: '',
      // 校验规则
      rules: {
        title: [{ required: true, message: '请输入标题内容', trigger: 'blur' }],
        cate_id: [
          { required: true, message: '请选择分类', trigger: ['blur', 'change'] },
          { validator: select, message: '请选择分类', trigger: ['blur', 'change'] }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }

    }
  },
  components: {
    quillEditor
  },
  methods: {
    async onSubmit (state) {
      this.form.state = state
      this.$refs.form.validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
      if (this.id) {
        console.log('修改')
        try {
        // 创建FormData对象并附加文件
          const formData = new FormData()
          formData.append('cover_img', this.form.cover_img)
          formData.append('id', this.id)
          formData.append('title', this.form.title)
          formData.append('cate_id', this.form.cate_id)
          formData.append('content', this.form.content)
          formData.append('state', this.form.state)
          const res = await changeArticle(formData)
          console.log(res)
          this.$router.push('/art-list')
        } catch (e) {
          alert(e)
        }
      } else {
        console.log('新增')
        try {
        // 创建FormData对象并附加文件
          const formData = new FormData()
          formData.append('cover_img', this.form.cover_img)
          formData.append('title', this.form.title)
          formData.append('cate_id', this.form.cate_id)
          formData.append('content', this.form.content)
          formData.append('state', this.form.state)
          await publishArticle(formData)
          this.$router.push('/art-list')
        } catch (e) {
          alert(e)
        }
      }
    },
    // select 失焦
    selectBlur () {
      console.log('失焦')
    },
    // quillEditor 失焦
    quillEditorBlur () {
      console.log('富文本失焦')
    },
    // 渲染分类数据
    async InitClassAction () {
      try {
        const res = await InitClass()
        // 等有数据时候使用
        this.classData = res.data
      } catch (e) {
        console.log(e)
      }
    },
    // 回显数据
    async getArticleAction (id) {
      try {
        const res = await getArticle(id)
        this.form.title = res.data.title
        this.form.cate_id = res.data.cate_id
        this.form.content = res.data.content
        this.form.state = res.data.state
        this.src = `http://big-event-vue-api-t.itheima.net${res.data.cover_img}`
        await fetch(this.src)
          .then(response => response.blob())
          .then(blob => {
            // 创建一个图片文件对象
            const imageFile = new File([blob], 'image.jpg', { type: 'image/jpeg' })
            this.form.cover_img = imageFile
          })
          .catch(error => {
            console.error('Error fetching image:', error)
          })
        console.log(this.form.cover_img)
      } catch (e) {
        console.log(e)
      }
    },
    // 封面图片变化
    Imgchange () {
      const file = this.$refs.inputFile.files[0]
      this.src = file ? URL.createObjectURL(file) : ''
      this.form.cover_img = file
      console.log(this.form.cover_img)
    }
  },
  created () {
    this.InitClassAction()
    const id = this.$route.query.id
    this.id = id
    if (this.id) {
      this.getArticleAction(this.id)
    }
  }
}
</script>

<style lang='scss' scoped>

  .box-card {
    width: 1126px;
    // 修改单元格左侧padding
    ::v-deep .el-table th.el-table__cell ,
    ::v-deep .el-table td.el-table__cell {
       padding-left: 14px;
       height: 42px;
    }
    // 修改表头字体颜色
    ::v-deep .el-table th.el-table__cell{
        color: rgba($color: #000000, $alpha: 0.4);
    }
    // 修改内容字体颜色
    ::v-deep .el-table td.el-table__cell{
        color: rgba($color: #131523, $alpha: 0.9);
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }
    ::v-deep el-card__body{
        padding: 30px;
    }
    // 修改表格样式
    .from{
        ::v-deep  .el-form{
          .el-form-item {
            display: flex;
            justify-content:start;
            font-size: 14px;
            .el-form-item__label{
                margin-right: 10px;
                padding: 0;
                height: 22px;
            }
            .el-input{
                width: 992px;
                height: 40px;
            }
            .quill-editor{
                width: 992px;
                .ql-toolbar {
                    display: flex;
                    justify-content: space-between;
                    .ql-formats{
                        display: flex;
                        justify-content: space-between;
                        margin: 0;
                    }
                }
                .ql-editor{
                    height: 120px;
                }
            }
            img{
                margin-left: 10px;
                width: 320px;
                height: 220px;
            }
          }
          .buttons{
            padding-left: 66px;
            // 按钮效果
            .sendButton,.saveButton{
                padding: 5px 16px;
                height: 32px;
            }
            .sendButton{
                width: 60px;
                background-color: #4F81FF ;
                color: #FFF;
                &:hover{
                    background-color:#608DFF ;
                }
            }
            .saveButton{
                width: 88px;
                background-color: #8f9397;
                color: #fff;
                &:hover{
                    background-color:#a1a6ac;
                }
            }
          }

        }
    }
  }
</style>
